import java.util.PriorityQueue;

//优先级队列_数据流中的第 K 大元素_
//https://leetcode.cn/problems/kth-largest-element-in-a-stream/description/
public class Test {
    public static void main(String[] args) {
        int[] nums = {4,5,8,2};
        KthLargest k = new KthLargest(3,nums);
        int[] nums2 = {3,5,10,9,4};
        for(int i = 0; i < 5 ; i++ ){
            System.out.println(k.add(nums2[i]));
        }
    }
}


class KthLargest {
    PriorityQueue<Integer> heap = new PriorityQueue<Integer>((a, b) -> a-b);//小根堆——注意这里：复习一下lambda表达式
                                                                            //不过呢，默认是小根堆，其实也不用传比较器

    int count = 0;
    public KthLargest(int k, int[] nums) {
        
        for(int num : nums){
            heap.add(num);
            if(heap.size() > k){//注意:堆大小的维护时机
                heap.poll();
            }
        }
    }

    public int add(int val) {
        /*if(val <= heap.peek()){
            return heap.peek();
        }else{
            heap.poll();
            heap.add(val);
            return heap.peek();
        }*/
        heap.add(val);
        if(heap.size() > count)
            heap.poll();
        return heap.peek();
    }
}

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest obj = new KthLargest(k, nums);
 * int param_1 = obj.add(val);
 */
